package web.tcp.test2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description
 * @className TestServer
 * @package web.tcp.test2
 * @author dongww@hsyuntai.com
 * @date 2020/3/11 16:00
 * @copyright 版权归 HSYUNTAI 所有
 */
public class TestServer {

    InputStreamReader isr, isr2;
    BufferedReader br, br2;
    PrintWriter pw;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestServer ts = new TestServer();
    }

    public TestServer() {
        try {
            ServerSocket ss = new ServerSocket(3002);
            System.out.println("服务器在监听3002端口...");
            //判断是否有客户端连接
            Socket s = ss.accept();
            //读取来自客户端的消息
            isr = new InputStreamReader(s.getInputStream());
            br = new BufferedReader(isr);

            pw = new PrintWriter(s.getOutputStream(), true);
            //接收从控制台输入的信息
            isr2 = new InputStreamReader(System.in);
            br2 = new BufferedReader(isr2);


            while (true) {

                String respone = br.readLine();
                if (respone.equals("再见")) {
                    System.out.println("对话结束");
                    s.close();
                    break;
                }
                System.out.println("客户端说：" + respone);

                System.out.println("请输入要发送到客户端的信息：");
                String info = br2.readLine();
                //将消息发送给客户端
                pw.println(info);
                if (info.equals("再见")) {
                    System.out.println("对话结束");
                    s.close();
                    break;
                }

            }

        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            if (br2 != null) {
                try {
                    br2.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (isr2 != null) {
                try {
                    isr2.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (pw != null) {
                pw.close();
            }

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }
}